import json
from jsonpath import jsonpath
from common.ds_base_api import CommonRequest


class CreateHeaders:

    def __init__(self):
        self.send_request = CommonRequest()

    # 读取config 文件
    def read_config_json(self):
        with open("../config/data.json", encoding="utf-8") as file:
            config_json = json.loads(file.read())
            return config_json

    # 获取Host
    def get_host(self):
        host = jsonpath(self.read_config_json(), "$..host")
        return host[0]

    # 获取Shopify 店铺名
    def get_store_name(self):
        shop_name = jsonpath(self.read_config_json(), "$..shop_name")
        return shop_name[0]

    # 获取 token
    def get_token(self):
        token = jsonpath(self.read_config_json(), "$..authorization")
        return token[0]

    # 获取DSID
    def get_strore_id(self):
        store_id = jsonpath(self.read_config_json(), "$..dsid")
        return store_id[0]

    def get_request_headers(self):
        headers = jsonpath(self.read_config_json(), "$..headers")
        return headers[0]

    # 写入账号token
    def write_user_token(self):
        token_resporse = self.send_request.choose_method(
            method='post',
            url="https://atc.dsers.com/uaa/api/1.0/login",
            # DSers 账号密码
            data='{"email": "testnew2@dsers.com","password": "123456"}',
            headers={'Content-Type': "application/json"})
        user_access_token = jsonpath(token_resporse.json(), "$..access_token")
        with open("../config/data.json", 'rb') as file:
            config_json = json.load(file)
            config_json['headers']['authorization'] = user_access_token[0]
        file.close()
        with open("../config/data.json", 'w') as file:
            json.dump(config_json, file)
        file.close()

    # 写入测试store_id
    def write_store_id(self):
        response = self.send_request.choose_method(
            method='get',
            url='https://atc.dsers.com/api/v1/users/info',
            headers={
                'Content-Type': "application/json",
                'authorization': self.get_token()
            },
            data=None
        )
        rt = json.loads(response.text)
        stores = rt['data']['stores']
        for store in stores:
            if store['shop_name'] == self.get_store_name():
                store_id = store['id']
                with open("../config/data.json", 'rb') as file:
                    config_json = json.load(file)
                    config_json['headers']['dsid'] = store_id
                file.close()
                with open("../config/data.json", 'w') as file:
                    json.dump(config_json, file)
                file.close()


if __name__ == '__main__':
    create_headers = CreateHeaders()
    print(create_headers.get_request_headers())
    print(str(create_headers.get_request_headers()))
